package paws.core

import scala.actors._
import java.io._

abstract class Logger(val name: String) extends Actor {
  import Actor._
  
  def act() {   
    var running: Boolean = true
    
    loop {
      if(!running) exit
      receive { 
        case Symbol("exit") => 
          running = false
          onTerminate
        case msg: String =>
          log(msg)
      } 
    }
  }
  
  def onTerminate(): Unit = ()  
  def log(msg: String)
  
  start()
}

class FileLogger(name: String, file: File) extends Logger(name) with BasicLogger {
  def this(name: String, filename: String) = this(name, new File(filename))
  protected override val out = new PrintStream(new FileOutputStream(file))
  override def onTerminate = out.close()
}

class ComboLogger(name:String, loggers: Logger*) extends Logger(name) {  
  override def log(msg: String) = loggers.foreach(_ ! msg)
  override def onTerminate = loggers.foreach(_ ! Symbol("exit"))
}

trait BasicLogger {
  _self: Logger =>
  
  private var count = 0
  protected val out: PrintStream = System.out
  
  def log(msg: String) {
    count += 1
    out.println( name + ":%010d".format(count) + ": " + msg)            
    out.flush
  }
  
  override def onTerminate(): Unit = out.flush
}


trait ErrorLogger extends BasicLogger {
  _self: Logger =>
  protected override val out = System.err
}